package com.hdy.javachatroomdemo.factory;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hdy.javachatroomdemo.Model.*;
import com.hdy.javachatroomdemo.constant.Constants;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.util.List;

@Component("fileTransferStrategy")
@Slf4j
public class FileTransfer extends AbstractMessageTransfer{
    @Autowired
    SessionMapper sessionMapper;
    @Autowired
    OnlineUserMapper onlineUserMapper;
    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    MessageMapper messageMapper;
    @SneakyThrows
    @Override
    public void sendMessage(MessageRequest request, User user) {
        System.out.println("接受的到的会话sessionId:"+request.getSessionId());
        //根据sessionId从数据库中获取相关的userId,由于前面已经实现过类似的方法这里直接调用
        List<Friend> friends=sessionMapper.getFriendBySessionId(request.getSessionId(),user.getUserId());
        //由于这个方法获取的是会话中除了本人以外其他的好友,但是我们进行响应的时候要给包括自己在内的所有人响应
        //因此添加上自己
        Friend new_friend=new Friend();
        new_friend.setFriendId(user.getUserId());
        new_friend.setFriendName(user.getUsername());
        friends.add(new_friend);
        //接着进行消息的响应
        //将friend挨个取出来进行转发
        for(Friend friend:friends){
            WebSocketSession session=onlineUserMapper.get(friend.getFriendId());
            //构建响应消息
            MessageResponse response=new MessageResponse();
            response.setContent(request.getContent());
            response.setFromName(user.getUsername());
            response.setSessionId(request.getSessionId());
            response.setFromId(user.getUserId());
            response.setType(Constants.FILE);
            //将Java对象转化成json字符串
            String jsonData=objectMapper.writeValueAsString(response);

            //有些客户端可能不在线,此时就不进行转发操作,而是等到客户端上线了自己调用getHistoryMessage方法来获取消息
            if(session==null){
                continue;
            }
            //进行转发,此处不能直接将字符串作为参数
            session.sendMessage(new TextMessage(jsonData));
        }
        //存入数据库值存一次!!
        //将消息存入数据库
        Message message = new Message();
        message.setFromId(user.getUserId());
        message.setSessionId(request.getSessionId());
        message.setContent(request.getContent());
        message.setType(Constants.FILE); // 设置消息类型为文件
        int ret=messageMapper.addMessage(message);
        System.out.println("插入消息影响行数:"+ret);
    }
}
